package com.zjitc.controller;

import com.zjitc.model.User;
import com.zjitc.service.UserService;
import com.zjitc.util.MailUtils;
import com.zjitc.util.RedisUtils;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import jdk.nashorn.internal.ir.RuntimeNode.Request;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * Create by IntelliJ IDEA
 *
 * @author: jsonor
 * @date-Time: 2018/4/16 16:14
 * @description:
 */
@Controller
public class UserController {

  @Autowired
  private UserService userService;

  @RequestMapping("/login")
  public String login(HttpSession session) {

    return "/WEB-INF/user/login.jsp";
  }

  @RequestMapping("/regist")
  public String regist() {
    return "/WEB-INF/user/regist.jsp";
  }

  @RequestMapping("/doRegist")
  public String doRegist(User user) {
    userService.doRegist(user);
    return "/WEB-INF/user/index.jsp";
  }


  @RequestMapping("/doLogin")
  public String doLogin(
      @RequestParam(name = "username") String username,
      @RequestParam(name = "password") String password,
      HttpSession session,
      String code) {

    User user = userService.doLogin(username, password);
    if (user != null) {
      String trueCode= (String) session.getAttribute("validatecCode");
      if(!code.equalsIgnoreCase(trueCode))
      {
        session.setAttribute("codeMsg","验证码错误");
        return "/WEB-INF/user/login.jsp";
      }
      session.setAttribute("user", user);
      return "/WEB-INF/user/index.jsp";
    } else {
      return "/WEB-INF/user/login.jsp";
    }
  }

  @RequestMapping("/logout")
  public String logout(HttpSession session) {
    session.removeAttribute("user");
    return "/WEB-INF/user/index.jsp";
  }


  @RequestMapping("/getPassword")
  public String forgetPassword() {
    return "/WEB-INF/user/forget.jsp";
  }

  @RequestMapping("/haveEmail")
  public String haveEamil(String username, String email) throws Exception {

    int Name = userService.findUsername(username);
    if (Name == 1) {
      String Email = userService.findEmailByUsername(username);
      if (Email.equals(email)) {
        String Token = String.valueOf(UUID.randomUUID());
        MailUtils.main(Token, Email);
        RedisUtils.add(username, Token);
        return "/WEB-INF/user/getNewPassword.jsp";
      } else {
        return "/WEB-INF/user/emailError.jsp";
      }
    }
    return "/WEB-INF/user/usernameError.jsp";

  }

  @RequestMapping("/updatePassword")
  public String updatePassword(String username, String password, String Token) {

    if (Token.equals(RedisUtils.find(username))) {
      userService.updatePassword(username, password);
      return "/WEB-INF/user/login.jsp";
    } else {
      return "/WEB-INF/user/tokenError.jsp";
    }

  }


}
